home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Internet Tools 1993 July / Internet Tools.iso / RockRidge / mail / pine / imap-3.0 / ANSI / c-client / mmdf.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-06-30  |  64.1 KB  |  2,033 lines

  1. /*
  2.  * Program:    MMDF mail routines
  3.  *
  4.  * Author:    Bruce W. Knipe <bwk@cyberstore.ca> from bezerk.c by:
  5.  *        Mark Crispin
  6.  *        Networks and Distributed Computing
  7.  *        Computing & Communications
  8.  *        University of Washington
  9.  *        Administration Building, AG-44
  10.  *        Seattle, WA  98195
  11.  *        Internet: MRC@CAC.Washington.EDU
  12.  *
  13.  * Date:    15 May 1993
  14.  * Last Edited:    30 June 1993
  15.  *
  16.  * Copyright 1993 by the University of Washington
  17.  *
  18.  *  Permission to use, copy, modify, and distribute this software and its
  19.  * documentation for any purpose and without fee is hereby granted, provided
  20.  * that the above copyright notice appears in all copies and that both the
  21.  * above copyright notice and this permission notice appear in supporting
  22.  * documentation, and that the name of the University of Washington not be
  23.  * used in advertising or publicity pertaining to distribution of the software
  24.  * without specific, written prior permission.  This software is made
  25.  * available "as is", and
  26.  * THE UNIVERSITY OF WASHINGTON DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED,
  27.  * WITH REGARD TO THIS SOFTWARE, INCLUDING WITHOUT LIMITATION ALL IMPLIED
  28.  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND IN
  29.  * NO EVENT SHALL THE UNIVERSITY OF WASHINGTON BE LIABLE FOR ANY SPECIAL,
  30.  * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  31.  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, TORT
  32.  * (INCLUDING NEGLIGENCE) OR STRICT LIABILITY, ARISING OUT OF OR IN CONNECTION
  33.  * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  34.  *
  35.  */
  36.  
  37. #include <stdio.h>
  38. #include <ctype.h>
  39. #include <netdb.h>
  40. #include <errno.h>
  41. extern int errno;        /* just in case */
  42. #include <signal.h>
  43. #include "mail.h"
  44. #include "osdep.h"
  45. #include <pwd.h>
  46. #include <sys/file.h>
  47. #include <sys/stat.h>
  48. #include <sys/time.h>
  49. #include "mmdf.h"
  50. #include "rfc822.h"
  51. #include "misc.h"
  52.  
  53. /* MMDF mail routines */
  54.  
  55.  
  56. /* Driver dispatch used by MAIL */
  57.  
  58. DRIVER mmdfdriver = {
  59.   "mmdf",            /* driver name */
  60.   (DRIVER *) NIL,        /* next driver */
  61.   mmdf_valid,            /* mailbox is valid for us */
  62.   mmdf_parameters,        /* manipulate parameters */
  63.   mmdf_find,            /* find mailboxes */
  64.   mmdf_find_bboards,        /* find bboards */
  65.   mmdf_find_all,        /* find all mailboxes */
  66.   mmdf_find_all_bboards,    /* find all bboards */
  67.   mmdf_subscribe,        /* subscribe to mailbox */
  68.   mmdf_unsubscribe,        /* unsubscribe from mailbox */
  69.   mmdf_subscribe_bboard,    /* subscribe to bboard */
  70.   mmdf_unsubscribe_bboard,    /* unsubscribe from bboard */
  71.   mmdf_create,            /* create mailbox */
  72.   mmdf_delete,            /* delete mailbox */
  73.   mmdf_rename,            /* rename mailbox */
  74.   mmdf_open,            /* open mailbox */
  75.   mmdf_close,            /* close mailbox */
  76.   mmdf_fetchfast,        /* fetch message "fast" attributes */
  77.   mmdf_fetchflags,        /* fetch message flags */
  78.   mmdf_fetchstructure,        /* fetch message envelopes */
  79.   mmdf_fetchheader,        /* fetch message header only */
  80.   mmdf_fetchtext,        /* fetch message body only */
  81.   mmdf_fetchbody,        /* fetch message body section */
  82.   mmdf_setflag,            /* set message flag */
  83.   mmdf_clearflag,        /* clear message flag */
  84.   mmdf_search,            /* search for message based on criteria */
  85.   mmdf_ping,            /* ping mailbox to see if still alive */
  86.   mmdf_check,            /* check for new messages */
  87.   mmdf_expunge,            /* expunge deleted messages */
  88.   mmdf_copy,            /* copy messages to another mailbox */
  89.   mmdf_move,            /* move messages to another mailbox */
  90.   mmdf_append,            /* append string message to mailbox */
  91.   mmdf_gc            /* garbage collect stream */
  92. };
  93.  
  94.                 /* prototype stream */
  95. MAILSTREAM mmdfproto = {&mmdfdriver};
  96.  
  97. /* MMDF mail validate mailbox
  98.  * Accepts: mailbox name
  99.  * Returns: our driver if name is valid, NIL otherwise
  100.  */
  101.  
  102. DRIVER *mmdf_valid (char *name)
  103. {
  104.   char tmp[MAILTMPLEN];
  105.   return mmdf_isvalid (name,tmp) ? &mmdfdriver : NIL;
  106. }
  107.  
  108.  
  109. /* MMDF mail test for valid mailbox
  110.  * Accepts: mailbox name
  111.  * Returns: T if valid, NIL otherwise
  112.  */
  113.  
  114. int mmdf_isvalid (char *name,char *tmp)
  115. {
  116.   int i,fd,ti,zn;
  117.   int ret = NIL;
  118.   char *s = tmp,*t;
  119.   struct stat sbuf;
  120.   struct hostent *host_name;
  121.   if (!lhostn) {        /* have local host yet? */
  122.     gethostname(tmp,MAILTMPLEN);/* get local host name */
  123.     lhostn = cpystr ((host_name = gethostbyname (tmp)) ?
  124.              host_name->h_name : tmp);
  125.   }
  126.                 /* INBOX is always accepted */
  127.   if (!strcmp (ucase (strcpy (tmp,name)),"INBOX")) return T;
  128.                 /* if file, get its status */
  129.   if (*name != '{' && (stat (mmdf_file (tmp,name),&sbuf) == 0) &&
  130.       ((fd = open (tmp,O_RDONLY,NIL)) >= 0)) {
  131.     if (sbuf.st_size == 0) {     /* allow empty file if not .txt */
  132.       if ((i = strlen (tmp)) < 4 || strcmp (tmp + i - 4 ,".txt"))
  133.     return LONGT;
  134.     }
  135.     else if ((read (fd,tmp,MAILTMPLEN-1) >= 0) &&
  136.          (tmp[0] == (char)0x01) && VALID (s,t,ti,zn)) ret = T;
  137.     close (fd);            /* close the file */
  138.   }
  139.   return ret;            /* return what we should */
  140. }
  141.  
  142. /* MMDF manipulate driver parameters
  143.  * Accepts: function code
  144.  *        function-dependent value
  145.  * Returns: function-dependent return value
  146.  */
  147.  
  148. void *mmdf_parameters (long function,void *value)
  149. {
  150.   fatal ("Invalid mmdf_parameters function");
  151. }
  152.  
  153. /* MMDF mail find list of mailboxes
  154.  * Accepts: mail stream
  155.  *        pattern to search
  156.  */
  157.  
  158. void mmdf_find (MAILSTREAM *stream,char *pat)
  159. {
  160.   void *s = NIL;
  161.   char *t,tmp[MAILTMPLEN];
  162.   while (t = sm_read (&s))    /* read subscription database */
  163.     if ((*t != '{') && strcmp (t,"INBOX") && pmatch (t,pat) &&
  164.     mmdf_isvalid (t,tmp)) mm_mailbox (t);
  165. }
  166.  
  167.  
  168. /* MMDF mail find list of bboards
  169.  * Accepts: mail stream
  170.  *        pattern to search
  171.  */
  172.  
  173. void mmdf_find_bboards (MAILSTREAM *stream,char *pat)
  174. {
  175.   /* Always a no-op */
  176. }
  177.  
  178. /* MMDF mail find list of all mailboxes
  179.  * Accepts: mail stream
  180.  *        pattern to search
  181.  */
  182.  
  183. void mmdf_find_all (MAILSTREAM *stream,char *pat)
  184. {
  185.   DIR *dirp;
  186.   struct direct *d;
  187.   char tmp[MAILTMPLEN],file[MAILTMPLEN];
  188.   int i = 0;
  189.   char *s,*t;
  190.   if (s = strrchr (pat,'/')) {    /* directory specified in pattern? */
  191.     strncpy (file,pat,i = (++s) - pat);
  192.     file[i] = '\0';        /* tie off prefix */
  193.     t = mmdf_file (tmp,pat);    /* make fully-qualified file name */
  194.                 /* tie off directory name */
  195.     if (s = strrchr (t,'/')) *s = '\0';
  196.   }
  197.   else t = myhomedir ();    /* use home directory to search */
  198.   if (dirp = opendir (t)) {    /* now open that directory */
  199.     while (d = readdir (dirp)) {/* for each directory entry */
  200.       strcpy (file + i,d->d_name);
  201.       if (pmatch (file,pat) && (mmdf_isvalid (file,tmp))) mm_mailbox (file);
  202.     }
  203.     closedir (dirp);        /* flush directory */
  204.   }
  205. }
  206.  
  207.  
  208. /* MMDF mail find list of all bboards
  209.  * Accepts: mail stream
  210.  *        pattern to search
  211.  */
  212.  
  213. void mmdf_find_all_bboards (MAILSTREAM *stream,char *pat)
  214. {
  215.   /* Always a no-op */
  216. }
  217.  
  218. /* MMDF mail subscribe to mailbox
  219.  * Accepts: mail stream
  220.  *        mailbox to add to subscription list
  221.  * Returns: T on success, NIL on failure
  222.  */
  223.  
  224. long mmdf_subscribe (MAILSTREAM *stream,char *mailbox)
  225. {
  226.   char tmp[MAILTMPLEN];
  227.   return sm_subscribe (mmdf_file (tmp,mailbox));
  228. }
  229.  
  230.  
  231. /* MMDF mail unsubscribe to mailbox
  232.  * Accepts: mail stream
  233.  *        mailbox to delete from subscription list
  234.  * Returns: T on success, NIL on failure
  235.  */
  236.  
  237. long mmdf_unsubscribe (MAILSTREAM *stream,char *mailbox)
  238. {
  239.   char tmp[MAILTMPLEN];
  240.   return sm_unsubscribe (mmdf_file (tmp,mailbox));
  241. }
  242.  
  243.  
  244. /* MMDF mail subscribe to bboard
  245.  * Accepts: mail stream
  246.  *        bboard to add to subscription list
  247.  * Returns: T on success, NIL on failure
  248.  */
  249.  
  250. long mmdf_subscribe_bboard (MAILSTREAM *stream,char *mailbox)
  251. {
  252.   return NIL;            /* never valid for MMDF */
  253. }
  254.  
  255.  
  256. /* MMDF mail unsubscribe to bboard
  257.  * Accepts: mail stream
  258.  *        bboard to delete from subscription list
  259.  * Returns: T on success, NIL on failure
  260.  */
  261.  
  262. long mmdf_unsubscribe_bboard (MAILSTREAM *stream,char *mailbox)
  263. {
  264.   return NIL;            /* never valid for MMDF */
  265. }
  266.  
  267. /* MMDF mail create mailbox
  268.  * Accepts: MAIL stream
  269.  *        mailbox name to create
  270.  * Returns: T on success, NIL on failure
  271.  */
  272.  
  273. long mmdf_create (MAILSTREAM *stream,char *mailbox)
  274. {
  275.   char tmp[MAILTMPLEN];
  276.   int i,fd;
  277.                 /* must be a ".txt" file */
  278.   if ((i = strlen (mailbox)) > 4 && !strcmp (mailbox + i - 4 ,".txt")) {
  279.     mm_log ("Can't create mailbox: name must not end with .txt",ERROR);
  280.     return NIL;
  281.   }
  282.   if ((fd = open (bezerk_file (tmp,mailbox),O_WRONLY|O_CREAT|O_EXCL,0600))<0) {
  283.     sprintf (tmp,"Can't create mailbox %s: %s",mailbox,strerror (errno));
  284.     mm_log (tmp,ERROR);
  285.     return NIL;
  286.   }
  287.   close (fd);            /* close the file */
  288.   return T;            /* return success */
  289. }
  290.  
  291.  
  292. /* MMDF mail delete mailbox
  293.  * Accepts: MAIL stream
  294.  *        mailbox name to delete
  295.  * Returns: T on success, NIL on failure
  296.  */
  297.  
  298. long mmdf_delete (MAILSTREAM *stream,char *mailbox)
  299. {
  300.   return mmdf_rename (stream,mailbox,NIL);
  301. }
  302.  
  303. /* MMDF mail rename mailbox
  304.  * Accepts: MAIL stream
  305.  *        old mailbox name
  306.  *        new mailbox name (or NIL for delete)
  307.  * Returns: T on success, NIL on failure
  308.  */
  309.  
  310. long mmdf_rename (MAILSTREAM *stream,char *old,char *new)
  311. {
  312.   long ret = T;
  313.   char tmp[MAILTMPLEN],file[MAILTMPLEN],lock[MAILTMPLEN],lockx[MAILTMPLEN];
  314.   int fd,ld;
  315.                 /* get the c-client lock */
  316.   if ((ld = open (lockname (lock,mmdf_file (file,old)),O_RDWR|O_CREAT,0666))
  317.       < 0) {
  318.     sprintf (tmp,"Can't get lock for mailbox %s: %s",old,strerror (errno));
  319.     mm_log (tmp,ERROR);
  320.     return NIL;
  321.   }
  322.                 /* lock out other c-clients */
  323.   if (flock (ld,LOCK_EX|LOCK_NB)) {
  324.     close (ld);            /* couldn't lock, give up on it then */
  325.     sprintf (tmp,"Mailbox %s is in use by another process",old);
  326.     mm_log (tmp,ERROR);
  327.     return NIL;
  328.   }
  329.                 /* lock out non c-client applications */
  330.   if ((fd = mmdf_lock (file,O_RDONLY,S_IREAD|S_IWRITE,lockx,LOCK_EX)) < 0) {
  331.     sprintf (tmp,"Can't lock mailbox %s: %s",old,strerror (errno));
  332.     mm_log (tmp,ERROR);
  333.     return NIL;
  334.   }
  335.                 /* do the rename or delete operation */
  336.   if (new ? rename (file,mmdf_file (tmp,new)) : unlink (file)) {
  337.     sprintf (tmp,"Can't %s mailbox %s: %s",new ? "rename" : "delete",old,
  338.          strerror (errno));
  339.     mm_log (tmp,ERROR);
  340.     ret = NIL;            /* set failure */
  341.   }
  342.   mmdf_unlock (fd,NIL,lockx);    /* unlock and close mailbox */
  343.   flock (ld,LOCK_UN);        /* release c-client lock lock */
  344.   close (ld);            /* close c-client lock */
  345.   unlink (lock);        /* and delete it */
  346.   return ret;            /* return success */
  347. }
  348.  
  349. /* MMDF mail open
  350.  * Accepts: Stream to open
  351.  * Returns: Stream on success, NIL on failure
  352.  */
  353.  
  354. MAILSTREAM *mmdf_open (MAILSTREAM *stream)
  355. {
  356.   long i;
  357.  
  358.   long retry = KODRETRY;    /* number of seconds to retry */
  359.   int fd;
  360.   char tmp[MAILTMPLEN];
  361.   struct stat sbuf;
  362.                 /* return prototype for OP_PROTOTYPE call */
  363.   if (!stream) return &mmdfproto;
  364.   if (LOCAL) {            /* close old file if stream being recycled */
  365.     mmdf_close (stream);    /* dump and save the changes */
  366.     stream->dtb = &mmdfdriver;/* reattach this driver */
  367.     mail_free_cache (stream);    /* clean up cache */
  368.   }
  369.   stream->local = fs_get (sizeof (MMDFLOCAL));
  370.                 /* canonicalize the stream mailbox name */
  371.   mmdf_file (tmp,stream->mailbox);
  372.   fs_give ((void **) &stream->mailbox);
  373.   stream->mailbox = cpystr (tmp);
  374.   /* You may wonder why LOCAL->name is needed.  It isn't at all obvious from
  375.    * the code.  The problem is that when a stream is recycled with another
  376.    * mailbox of the same type, the driver's close method isn't called because
  377.    * it could be IMAP and closing then would defeat the entire point of
  378.    * recycling.  Hence there is code in the file drivers to call the close
  379.    * method such as what appears above.  The problem is, by this point,
  380.    * mail_open() has already changed the stream->mailbox name to point to the
  381.    * new name, and mmdf_close() needs the old name.
  382.    */
  383.   LOCAL->name = cpystr (tmp);    /* local copy for recycle case */
  384.                 /* build name of our lock file */
  385.   LOCAL->lname = cpystr (lockname (tmp,stream->mailbox));
  386.   LOCAL->ld = NIL;        /* no state locking yet */
  387.   LOCAL->filesize = 0;        /* initialize file information */
  388.   LOCAL->filetime = 0;
  389.   LOCAL->msgs = NIL;        /* no cache yet */
  390.   LOCAL->cachesize = 0;
  391.   LOCAL->buf = (char *) fs_get ((LOCAL->buflen = CHUNK) + 1);
  392.   stream->sequence++;        /* bump sequence number */
  393.  
  394.   LOCAL->dirty = NIL;        /* no update yet */
  395.                 /* make lock for read/write access */
  396.   if (!stream->readonly) while (retry) {
  397.                 /* get a new file handle each time */
  398.     if ((fd = open (LOCAL->lname,O_RDWR|O_CREAT,0666)) < 0)
  399.       mm_log ("Can't open mailbox lock, access is readonly",WARN);
  400.                 /* can get the lock? */
  401.     if (flock (fd,LOCK_EX|LOCK_NB)) {
  402.       if (retry-- == KODRETRY) {/* no, first time through? */
  403.                 /* yes, get other process' PID */
  404.     if (!fstat (fd,&sbuf) && (i = min (sbuf.st_size,MAILTMPLEN)) &&
  405.         (read (fd,tmp,i) == i) && (i = atol (tmp))) {
  406.       kill (i,SIGUSR2);    /* send the Kiss Of Death */
  407.       sprintf (tmp,"Trying to get mailbox lock from process %ld",i);
  408.       mm_log (tmp,WARN);
  409.     }
  410.     else retry = 0;        /* give up */
  411.       }
  412.       close (fd);        /* get a new handle next time around */
  413.       if (retry) sleep (1);    /* wait a second before trying again */
  414.       else mm_log ("Mailbox is open by another process, access is readonly",
  415.            WARN);
  416.     }
  417.     else {            /* got the lock, nobody else can alter state */
  418.       LOCAL->ld = fd;        /* note lock's fd */
  419.       chmod (LOCAL->lname,0666);/* make sure mode OK (don't use fchmod()) */
  420.                 /* note our PID in the lock */
  421.       sprintf (tmp,"%d",getpid ());
  422.       write (fd,tmp,strlen (tmp));
  423.       fsync (fd);        /* make sure it's available */
  424.       retry = 0;        /* no more need to try */
  425.     }
  426.   }
  427.  
  428.                 /* parse mailbox */
  429.   stream->nmsgs = stream->recent = 0;
  430.                 /* will we be able to get write access? */
  431.   if (LOCAL->ld && access (LOCAL->name,W_OK) && (errno == EACCES)) {
  432.     mm_log ("Can't get write access to mailbox, access is readonly",WARN);
  433.     flock (LOCAL->ld,LOCK_UN);    /* release the lock */
  434.     close (LOCAL->ld);        /* close the lock file */
  435.     LOCAL->ld = NIL;        /* no more lock fd */
  436.     unlink (LOCAL->lname);    /* delete it */
  437.     fs_give ((void **) &LOCAL->lname);
  438.   }
  439.                 /* parse mailbox */
  440.   if ((fd = mmdf_parse (stream,tmp,LOCK_SH)) >= 0) {
  441.     mmdf_unlock (fd,stream,tmp);
  442.     mail_unlock (stream);
  443.   }
  444.   if (!LOCAL) return NIL;    /* failure if stream died */
  445.   stream->readonly = !LOCAL->ld;/* make sure upper level knows readonly */
  446.                 /* notify about empty mailbox */
  447.   if (!(stream->nmsgs || stream->silent)) mm_log ("Mailbox is empty",NIL);
  448.   return stream;        /* return stream alive to caller */
  449. }
  450.  
  451. /* MMDF mail close
  452.  * Accepts: MAIL stream
  453.  */
  454.  
  455. void mmdf_close (MAILSTREAM *stream)
  456. {
  457.   int fd;
  458.   int silent = stream->silent;
  459.   char lock[MAILTMPLEN];
  460.   if (LOCAL && LOCAL->ld) {    /* is stream alive? */
  461.     stream->silent = T;        /* note this stream is dying */
  462.                 /* lock mailbox and parse new messages */
  463.     if (LOCAL->dirty && (fd = mmdf_parse (stream,lock,LOCK_EX)) >= 0) {
  464.                 /* dump any changes not saved yet */
  465.       if (mmdf_extend    (stream,fd,"Close failed to update mailbox"))
  466.     mmdf_save (stream,fd);
  467.                 /* flush locks */
  468.       mmdf_unlock (fd,stream,lock);
  469.       mail_unlock (stream);
  470.     }
  471.     stream->silent = silent;    /* restore previous status */
  472.   }
  473.   mmdf_abort (stream);    /* now punt the file and local data */
  474. }
  475.  
  476.  
  477. /* MMDF mail fetch fast information
  478.  * Accepts: MAIL stream
  479.  *        sequence
  480.  */
  481.  
  482. void mmdf_fetchfast (MAILSTREAM *stream,char *sequence)
  483. {
  484.   return;            /* no-op for local mail */
  485. }
  486.  
  487.  
  488. /* MMDF mail fetch flags
  489.  * Accepts: MAIL stream
  490.  *        sequence
  491.  */
  492.  
  493. void mmdf_fetchflags (MAILSTREAM *stream,char *sequence)
  494. {
  495.   return;            /* no-op for local mail */
  496. }
  497.  
  498. /* MMDF mail fetch structure
  499.  * Accepts: MAIL stream
  500.  *        message # to fetch
  501.  *        pointer to return body
  502.  * Returns: envelope of this message, body returned in body value
  503.  *
  504.  * Fetches the "fast" information as well
  505.  */
  506.  
  507. ENVELOPE *mmdf_fetchstructure (MAILSTREAM *stream,long msgno,BODY **body)
  508. {
  509.   ENVELOPE **env;
  510.   BODY **b;
  511.   STRING bs;
  512.   LONGCACHE *lelt;
  513.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  514.   long i = max (m->headersize,m->bodysize);
  515.   if (stream->scache) {        /* short cache */
  516.     if (msgno != stream->msgno){/* flush old poop if a different message */
  517.       mail_free_envelope (&stream->env);
  518.       mail_free_body (&stream->body);
  519.     }
  520.     stream->msgno = msgno;
  521.     env = &stream->env;        /* get pointers to envelope and body */
  522.     b = &stream->body;
  523.   }
  524.   else {            /* long cache */
  525.     lelt = mail_lelt (stream,msgno);
  526.     env = &lelt->env;        /* get pointers to envelope and body */
  527.     b = &lelt->body;
  528.   }
  529.   if ((body && !*b) || !*env) {    /* have the poop we need? */
  530.     mail_free_envelope (env);    /* flush old envelope and body */
  531.     mail_free_body (b);
  532.     if (i > LOCAL->buflen) {    /* make sure enough buffer space */
  533.       fs_give ((void **) &LOCAL->buf);
  534.       LOCAL->buf = (char *) fs_get ((LOCAL->buflen = i) + 1);
  535.     }
  536.     INIT (&bs,mail_string,(void *) m->body,m->bodysize);
  537.                 /* parse envelope and body */
  538.     rfc822_parse_msg (env,body ? b : NIL,m->header,m->headersize,&bs,lhostn,
  539.               LOCAL->buf);
  540.   }
  541.   if (body) *body = *b;        /* return the body */
  542.   return *env;            /* return the envelope */
  543. }
  544.  
  545. /* Bezerk mail snarf message, only for Tenex driver
  546.  * Accepts: MAIL stream
  547.  *        message # to snarf
  548.  *        pointer to size to return
  549.  * Returns: message text in RFC822 format
  550.  */
  551.  
  552. char *bezerk_snarf (MAILSTREAM *stream,long msgno,long *size)
  553. {
  554.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  555.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  556.   if (((*size = m->headersize + m->bodysize) > LOCAL->buflen) ||
  557.       LOCAL->buflen > CHUNK) {    /* make sure stream can hold the text */
  558.                 /* fs_resize would do an unnecessary copy */
  559.     fs_give ((void **) &LOCAL->buf);
  560.     LOCAL->buf = (char *) fs_get((LOCAL->buflen = max (*size,(long) CHUNK))+1);
  561.   }
  562.                 /* copy the text */
  563.   if (m->headersize) memcpy (LOCAL->buf,m->header,m->headersize);
  564.   if (m->bodysize) memcpy (LOCAL->buf + m->headersize,m->body,m->bodysize);
  565.   LOCAL->buf[*size] = '\0';    /* tie off string */
  566.   return LOCAL->buf;
  567. }
  568.  
  569. /* MMDF mail fetch message header
  570.  * Accepts: MAIL stream
  571.  *        message # to fetch
  572.  * Returns: message header in RFC822 format
  573.  */
  574.  
  575. char *mmdf_fetchheader (MAILSTREAM *stream,long msgno)
  576. {
  577.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  578.                 /* copy the string */
  579.   return strcrlfcpy (&LOCAL->buf,&LOCAL->buflen,m->header,m->headersize);
  580. }
  581.  
  582.  
  583. /* MMDF mail fetch message text (body only)
  584.  * Accepts: MAIL stream
  585.  *        message # to fetch
  586.  * Returns: message text in RFC822 format
  587.  */
  588.  
  589. char *mmdf_fetchtext (MAILSTREAM *stream,long msgno)
  590. {
  591.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  592.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  593.   if (!elt->seen) {        /* if message not seen */
  594.     elt->seen = T;        /* mark message as seen */
  595.                 /* recalculate Status/X-Status lines */
  596.     mmdf_update_status (m->status,elt);
  597.     LOCAL->dirty = T;        /* note stream is now dirty */
  598.   }
  599.   return strcrlfcpy (&LOCAL->buf,&LOCAL->buflen,m->body,m->bodysize);
  600. }
  601.  
  602. /* MMDF fetch message body as a structure
  603.  * Accepts: Mail stream
  604.  *        message # to fetch
  605.  *        section specifier
  606.  *        pointer to length
  607.  * Returns: pointer to section of message body
  608.  */
  609.  
  610. char *mmdf_fetchbody (MAILSTREAM *stream,long m,char *s,unsigned long *len)
  611. {
  612.   BODY *b;
  613.   PART *pt;
  614.   unsigned long i;
  615.   char *base = LOCAL->msgs[m - 1]->body;
  616.   unsigned long offset = 0;
  617.   MESSAGECACHE *elt = mail_elt (stream,m);
  618.                 /* make sure have a body */
  619.   if (!(mmdf_fetchstructure (stream,m,&b) && b && s && *s &&
  620.     ((i = strtol (s,&s,10)) > 0))) return NIL;
  621.   do {                /* until find desired body part */
  622.                 /* multipart content? */
  623.     if (b->type == TYPEMULTIPART) {
  624.       pt = b->contents.part;    /* yes, find desired part */
  625.       while (--i && (pt = pt->next));
  626.       if (!pt) return NIL;    /* bad specifier */
  627.                 /* note new body, check valid nesting */
  628.       if (((b = &pt->body)->type == TYPEMULTIPART) && !*s) return NIL;
  629.       offset = pt->offset;    /* get new offset */
  630.     }
  631.     else if (i != 1) return NIL;/* otherwise must be section 1 */
  632.                 /* need to go down further? */
  633.     if (i = *s) switch (b->type) {
  634.     case TYPEMESSAGE:        /* embedded message */
  635.       offset = b->contents.msg.offset;
  636.       b = b->contents.msg.body;    /* get its body, drop into multipart case */
  637.     case TYPEMULTIPART:        /* multipart, get next section */
  638.       if ((*s++ == '.') && (i = strtol (s,&s,10)) > 0) break;
  639.     default:            /* bogus subpart specification */
  640.       return NIL;
  641.     }
  642.   } while (i);
  643.                 /* lose if body bogus */
  644.   if ((!b) || b->type == TYPEMULTIPART) return NIL;
  645.   if (!elt->seen) {        /* if message not seen */
  646.     elt->seen = T;        /* mark message as seen */
  647.                 /* recalculate Status/X-Status lines */
  648.     mmdf_update_status (LOCAL->msgs[m - 1]->status,elt);
  649.     LOCAL->dirty = T;        /* note stream is now dirty */
  650.   }
  651.   return rfc822_contents (&LOCAL->buf,&LOCAL->buflen,len,base + offset,
  652.               b->size.ibytes,b->encoding);
  653. }
  654.  
  655. /* MMDF mail set flag
  656.  * Accepts: MAIL stream
  657.  *        sequence
  658.  *        flag(s)
  659.  */
  660.  
  661. void mmdf_setflag (MAILSTREAM *stream,char *sequence,char *flag)
  662. {
  663.   MESSAGECACHE *elt;
  664.   long i;
  665.   short f = mmdf_getflags (stream,flag);
  666.   if (!f) return;        /* no-op if no flags to modify */
  667.                 /* get sequence and loop on it */
  668.   if (mail_sequence (stream,sequence)) for (i = 1; i <= stream->nmsgs; i++)
  669.     if ((elt = mail_elt (stream,i))->sequence) {
  670.                 /* set all requested flags */
  671.       if (f&fSEEN) elt->seen = T;
  672.       if (f&fDELETED) elt->deleted = T;
  673.       if (f&fFLAGGED) elt->flagged = T;
  674.       if (f&fANSWERED) elt->answered = T;
  675.                 /* recalculate Status/X-Status lines */
  676.       mmdf_update_status (LOCAL->msgs[i - 1]->status,elt);
  677.       LOCAL->dirty = T;        /* note stream is now dirty */
  678.     }
  679. }
  680.  
  681.  
  682. /* MMDF mail clear flag
  683.  * Accepts: MAIL stream
  684.  *        sequence
  685.  *        flag(s)
  686.  */
  687.  
  688. void mmdf_clearflag (MAILSTREAM *stream,char *sequence,char *flag)
  689. {
  690.   MESSAGECACHE *elt;
  691.   long i;
  692.   short f = mmdf_getflags (stream,flag);
  693.   if (!f) return;        /* no-op if no flags to modify */
  694.                 /* get sequence and loop on it */
  695.   if (mail_sequence (stream,sequence)) for (i = 1; i <= stream->nmsgs; i++)
  696.     if ((elt = mail_elt (stream,i))->sequence) {
  697.                 /* clear all requested flags */
  698.       if (f&fSEEN) elt->seen = NIL;
  699.       if (f&fDELETED) elt->deleted = NIL;
  700.       if (f&fFLAGGED) elt->flagged = NIL;
  701.       if (f&fANSWERED) elt->answered = NIL;
  702.                 /* recalculate Status/X-Status lines */
  703.       mmdf_update_status (LOCAL->msgs[i - 1]->status,elt);
  704.       LOCAL->dirty = T;        /* note stream is now dirty */
  705.     }
  706. }
  707.  
  708. /* MMDF mail search for messages
  709.  * Accepts: MAIL stream
  710.  *        search criteria
  711.  */
  712.  
  713. void mmdf_search (MAILSTREAM *stream,char *criteria)
  714. {
  715.   long i,n;
  716.   char *d;
  717.   search_t f;
  718.                 /* initially all searched */
  719.   for (i = 1; i <= stream->nmsgs; ++i) mail_elt (stream,i)->searched = T;
  720.                 /* get first criterion */
  721.   if (criteria && (criteria = strtok (criteria," "))) {
  722.                 /* for each criterion */
  723.     for (; criteria; (criteria = strtok (NIL," "))) {
  724.       f = NIL; d = NIL; n = 0;    /* init then scan the criterion */
  725.       switch (*ucase (criteria)) {
  726.       case 'A':            /* possible ALL, ANSWERED */
  727.     if (!strcmp (criteria+1,"LL")) f = mmdf_search_all;
  728.     else if (!strcmp (criteria+1,"NSWERED")) f = mmdf_search_answered;
  729.     break;
  730.       case 'B':            /* possible BCC, BEFORE, BODY */
  731.     if (!strcmp (criteria+1,"CC"))
  732.       f = mmdf_search_string (mmdf_search_bcc,&d,&n);
  733.     else if (!strcmp (criteria+1,"EFORE"))
  734.       f = mmdf_search_date (mmdf_search_before,&n);
  735.     else if (!strcmp (criteria+1,"ODY"))
  736.       f = mmdf_search_string (mmdf_search_body,&d,&n);
  737.     break;
  738.       case 'C':            /* possible CC */
  739.     if (!strcmp (criteria+1,"C")) 
  740.       f = mmdf_search_string (mmdf_search_cc,&d,&n);
  741.     break;
  742.       case 'D':            /* possible DELETED */
  743.     if (!strcmp (criteria+1,"ELETED")) f = mmdf_search_deleted;
  744.     break;
  745.       case 'F':            /* possible FLAGGED, FROM */
  746.     if (!strcmp (criteria+1,"LAGGED")) f = mmdf_search_flagged;
  747.     else if (!strcmp (criteria+1,"ROM"))
  748.       f = mmdf_search_string (mmdf_search_from,&d,&n);
  749.     break;
  750.       case 'K':            /* possible KEYWORD */
  751.     if (!strcmp (criteria+1,"EYWORD"))
  752.       f = mmdf_search_flag (mmdf_search_keyword,&d);
  753.     break;
  754.       case 'N':            /* possible NEW */
  755.     if (!strcmp (criteria+1,"EW")) f = mmdf_search_new;
  756.     break;
  757.  
  758.       case 'O':            /* possible OLD, ON */
  759.     if (!strcmp (criteria+1,"LD")) f = mmdf_search_old;
  760.     else if (!strcmp (criteria+1,"N"))
  761.       f = mmdf_search_date (mmdf_search_on,&n);
  762.     break;
  763.       case 'R':            /* possible RECENT */
  764.     if (!strcmp (criteria+1,"ECENT")) f = mmdf_search_recent;
  765.     break;
  766.       case 'S':            /* possible SEEN, SINCE, SUBJECT */
  767.     if (!strcmp (criteria+1,"EEN")) f = mmdf_search_seen;
  768.     else if (!strcmp (criteria+1,"INCE"))
  769.       f = mmdf_search_date (mmdf_search_since,&n);
  770.     else if (!strcmp (criteria+1,"UBJECT"))
  771.       f = mmdf_search_string (mmdf_search_subject,&d,&n);
  772.     break;
  773.       case 'T':            /* possible TEXT, TO */
  774.     if (!strcmp (criteria+1,"EXT"))
  775.       f = mmdf_search_string (mmdf_search_text,&d,&n);
  776.     else if (!strcmp (criteria+1,"O"))
  777.       f = mmdf_search_string (mmdf_search_to,&d,&n);
  778.     break;
  779.       case 'U':            /* possible UN* */
  780.     if (criteria[1] == 'N') {
  781.       if (!strcmp (criteria+2,"ANSWERED")) f = mmdf_search_unanswered;
  782.       else if (!strcmp (criteria+2,"DELETED")) f = mmdf_search_undeleted;
  783.       else if (!strcmp (criteria+2,"FLAGGED")) f = mmdf_search_unflagged;
  784.       else if (!strcmp (criteria+2,"KEYWORD"))
  785.         f = mmdf_search_flag (mmdf_search_unkeyword,&d);
  786.       else if (!strcmp (criteria+2,"SEEN")) f = mmdf_search_unseen;
  787.     }
  788.     break;
  789.       default:            /* we will barf below */
  790.     break;
  791.       }
  792.       if (!f) {            /* if can't determine any criteria */
  793.     sprintf (LOCAL->buf,"Unknown search criterion: %.30s",criteria);
  794.     mm_log (LOCAL->buf,ERROR);
  795.     return;
  796.       }
  797.                 /* run the search criterion */
  798.       for (i = 1; i <= stream->nmsgs; ++i)
  799.     if (mail_elt (stream,i)->searched && !(*f) (stream,i,d,n))
  800.       mail_elt (stream,i)->searched = NIL;
  801.     }
  802.                 /* report search results to main program */
  803.     for (i = 1; i <= stream->nmsgs; ++i)
  804.       if (mail_elt (stream,i)->searched) mail_searched (stream,i);
  805.   }
  806. }
  807.  
  808. /* MMDF mail ping mailbox
  809.  * Accepts: MAIL stream
  810.  * Returns: T if stream alive, else NIL
  811.  * No-op for readonly files, since read/writer can expunge it from under us!
  812.  */
  813.  
  814. long mmdf_ping (MAILSTREAM *stream)
  815. {
  816.   char lock[MAILTMPLEN];
  817.   struct stat sbuf;
  818.   int fd;
  819.                 /* does he want to give up readwrite? */
  820.   if (stream->readonly && LOCAL->ld) {
  821.     flock (LOCAL->ld,LOCK_UN);    /* yes, release the lock */
  822.     close (LOCAL->ld);        /* close the lock file */
  823.     LOCAL->ld = NIL;        /* no more lock fd */
  824.     unlink (LOCAL->lname);    /* delete it */
  825.     fs_give ((void **) &LOCAL->lname);
  826.   }
  827.                 /* make sure it is alright to do this at all */
  828.   if (LOCAL && LOCAL->ld && !stream->lock) {
  829.                 /* get current mailbox size */
  830.     stat (LOCAL->name,&sbuf);    /* parse if mailbox changed */
  831.     if ((sbuf.st_size != LOCAL->filesize) &&
  832.     ((fd = mmdf_parse (stream,lock,LOCK_SH)) >= 0)) {
  833.                 /* unlock mailbox */
  834.       mmdf_unlock (fd,stream,lock);
  835.       mail_unlock (stream);    /* and stream */
  836.     }
  837.   }
  838.   return LOCAL ? T : NIL;    /* return if still alive */
  839. }
  840.  
  841. /* MMDF mail check mailbox
  842.  * Accepts: MAIL stream
  843.  * No-op for readonly files, since read/writer can expunge it from under us!
  844.  */
  845.  
  846. void mmdf_check (MAILSTREAM *stream)
  847. {
  848.   char lock[MAILTMPLEN];
  849.   int fd;
  850.                 /* parse and lock mailbox */
  851.   if (LOCAL && LOCAL->ld && ((fd = mmdf_parse (stream,lock,LOCK_EX)) >= 0)) {
  852.     if (LOCAL->dirty && mmdf_extend (stream,fd,"Unable to update mailbox"))
  853.       mmdf_save (stream,fd);    /* dump checkpoint if needed */
  854.                 /* flush locks */
  855.     mmdf_unlock (fd,stream,lock);
  856.     mail_unlock (stream);
  857.   }
  858.   if (LOCAL && LOCAL->ld) mm_log ("Check completed",NIL);
  859. }
  860.  
  861. /* MMDF mail expunge mailbox
  862.  * Accepts: MAIL stream
  863.  */
  864.  
  865. void mmdf_expunge (MAILSTREAM *stream)
  866. {
  867.   int fd,j;
  868.   long i = 1;
  869.   long n = 0;
  870.   unsigned long recent;
  871.   MESSAGECACHE *elt;
  872.   char *r = "No messages deleted, so no update needed";
  873.   char lock[MAILTMPLEN];
  874.   if (LOCAL && LOCAL->ld) {    /* parse and lock mailbox */
  875.     if ((fd = mmdf_parse (stream,lock,LOCK_EX)) >= 0) {
  876.       recent = stream->recent;    /* get recent now that new ones parsed */
  877.       while ((j = (i<=stream->nmsgs)) && !(elt = mail_elt (stream,i))->deleted)
  878.     i++;            /* find first deleted message */
  879.       if (j) {            /* found one? */
  880.                 /* make sure we can do the worst case thing */
  881.     if (mmdf_extend (stream,fd,"Unable to expunge mailbox")) {
  882.       do {            /* flush deleted messages */
  883.         if ((elt = mail_elt (stream,i))->deleted) {
  884.                 /* if recent, note one less recent message */
  885.           if (elt->recent) --recent;
  886.                 /* flush local cache entry */
  887.           fs_give ((void **) &LOCAL->msgs[i - 1]);
  888.           for (j = i; j < stream->nmsgs; j++)
  889.         LOCAL->msgs[j - 1] = LOCAL->msgs[j];
  890.           LOCAL->msgs[stream->nmsgs - 1] = NIL;
  891.                 /* notify upper levels */
  892.           mail_expunged (stream,i);
  893.           n++;        /* count another expunged message */
  894.         }
  895.         else i++;        /* otherwise try next message */
  896.       } while (i <= stream->nmsgs);
  897.                 /* dump checkpoint of the results */
  898.       mmdf_save (stream,fd);
  899.       sprintf ((r = LOCAL->buf),"Expunged %d messages",n);
  900.     }
  901.       }
  902.                 /* notify upper level, free locks */
  903.       mail_exists (stream,stream->nmsgs);
  904.       mail_recent (stream,recent);
  905.       mmdf_unlock (fd,stream,lock);
  906.       mail_unlock (stream);
  907.     }
  908.   }
  909.   else r = "Expunge ignored on readonly mailbox";
  910.   if (LOCAL && !stream->silent) mm_log (r,NIL);
  911. }
  912.  
  913. /* MMDF mail copy message(s)
  914.  * Accepts: MAIL stream
  915.  *        sequence
  916.  *        destination mailbox
  917.  * Returns: T if copy successful, else NIL
  918.  */
  919.  
  920. long mmdf_copy (MAILSTREAM *stream,char *sequence,char *mailbox)
  921. {
  922.                 /* copy the messages */
  923.   return (mail_sequence (stream,sequence)) ?
  924.     mmdf_copy_messages (stream,mailbox) : NIL;
  925. }
  926.  
  927.  
  928. /* MMDF mail move message(s)
  929.  * Accepts: MAIL stream
  930.  *        sequence
  931.  *        destination mailbox
  932.  * Returns: T if move successful, else NIL
  933.  */
  934.  
  935. long mmdf_move (MAILSTREAM *stream,char *sequence,char *mailbox)
  936. {
  937.   long i;
  938.   MESSAGECACHE *elt;
  939.   if (!(mail_sequence (stream,sequence) &&
  940.     mmdf_copy_messages (stream,mailbox))) return NIL;
  941.                 /* delete all requested messages */
  942.   for (i = 1; i <= stream->nmsgs; i++)
  943.     if ((elt = mail_elt (stream,i))->sequence) {
  944.       elt->deleted = T;        /* mark message deleted */
  945.                 /* recalculate Status/X-Status lines */
  946.       mmdf_update_status (LOCAL->msgs[i - 1]->status,elt);
  947.       LOCAL->dirty = T;        /* note stream is now dirty */
  948.     }
  949.   return T;
  950. }
  951.  
  952. /* MMDF mail append message from stringstruct
  953.  * Accepts: MAIL stream
  954.  *        destination mailbox
  955.  *        stringstruct of messages to append
  956.  * Returns: T if append successful, else NIL
  957.  */
  958.  
  959. long mmdf_append (MAILSTREAM *stream,char *mailbox,STRING *message)
  960. {
  961.   struct stat sbuf;
  962.   int fd;
  963.   char c,tmp[MAILTMPLEN],lock[MAILTMPLEN];
  964.   int i = 0;
  965.   char *s = tmp;
  966.   long t = time (0);
  967.   long size = SIZE (message);
  968.   if ((fd = mmdf_lock (mmdf_file (tmp,mailbox),O_WRONLY|O_APPEND|O_CREAT,
  969.              S_IREAD|S_IWRITE,lock,LOCK_EX)) < 0) {
  970.     sprintf (tmp,"Can't open append mailbox: %s",strerror (errno));
  971.     mm_log (tmp,ERROR);
  972.     return NIL;
  973.   }
  974.   mm_critical (stream);        /* go critical */
  975.   fstat (fd,&sbuf);        /* get current file size */
  976.   sprintf (tmp,"From %s@%s %s",myusername (),lhostn,ctime (&t));
  977.                 /* write header */
  978.   if (write (fd,tmp,strlen (tmp)) < 0) {
  979.     sprintf (tmp,"Header write failed: %s",strerror (errno));
  980.     mm_log (tmp,ERROR);
  981.     ftruncate (fd,sbuf.st_size);
  982.   }  
  983.   else while (size--) {        /* copy text, tossing out CR's */
  984.     if ((c = SNX (message)) != '\015') s[i++] = c;
  985.                 /* dump if filled buffer or no more data */
  986.     if ((!size) || (i == MAILTMPLEN)) {
  987.       if ((write (fd,tmp,i)) < 0) {
  988.     sprintf (tmp,"Message append failed: %s",strerror (errno));
  989.     mm_log (tmp,ERROR);
  990.     ftruncate (fd,sbuf.st_size);
  991.     break;
  992.       }
  993.       i = 0;            /* restart buffer */
  994.                 /* write out final newline if at end */
  995.       if (!size) write (fd,"\n",1);
  996.     }
  997.   }
  998.   fsync (fd);            /* force out the update */
  999.   mmdf_unlock (fd,NIL,lock);    /* unlock and close mailbox */
  1000.   mm_nocritical (stream);    /* release critical */
  1001.   return T;            /* return success */
  1002. }
  1003.  
  1004. /* MMDF garbage collect stream
  1005.  * Accepts: Mail stream
  1006.  *        garbage collection flags
  1007.  */
  1008.  
  1009. void mmdf_gc (MAILSTREAM *stream,long gcflags)
  1010. {
  1011.   /* nothing here for now */
  1012. }
  1013.  
  1014. /* Internal routines */
  1015.  
  1016.  
  1017. /* MMDF mail abort stream
  1018.  * Accepts: MAIL stream
  1019.  */
  1020.  
  1021. void mmdf_abort (MAILSTREAM *stream)
  1022. {
  1023.   long i;
  1024.   if (LOCAL) {            /* only if a file is open */
  1025.     if (LOCAL->name) fs_give ((void **) &LOCAL->name);
  1026.     if (LOCAL->ld) {        /* have a mailbox lock? */
  1027.       flock (LOCAL->ld,LOCK_UN);/* yes, release the lock */
  1028.       close (LOCAL->ld);    /* close the lock file */
  1029.       unlink (LOCAL->lname);    /* and delete it */
  1030.     }
  1031.     fs_give ((void **) &LOCAL->lname);
  1032.     if (LOCAL->msgs) {        /* free local cache */
  1033.       for (i = 0; i < stream->nmsgs; ++i) fs_give ((void **) &LOCAL->msgs[i]);
  1034.       fs_give ((void **) &LOCAL->msgs);
  1035.     }
  1036.                 /* free local text buffers */
  1037.     if (LOCAL->buf) fs_give ((void **) &LOCAL->buf);
  1038.                 /* nuke the local data */
  1039.     fs_give ((void **) &stream->local);
  1040.     stream->dtb = NIL;        /* log out the DTB */
  1041.   }
  1042. }
  1043.  
  1044.  
  1045. /* MMDF mail generate file string
  1046.  * Accepts: temporary buffer to write into
  1047.  *        mailbox name string
  1048.  * Returns: local file string
  1049.  */
  1050.  
  1051.  
  1052. char *mmdf_file (char *dst,char *name)
  1053. {
  1054.   struct passwd *pw;
  1055.   char *s,*t,tmp[MAILTMPLEN];
  1056.   switch (*name) {
  1057.   case '/':            /* absolute file path */
  1058.     strcpy (dst,name);        /* copy the mailbox name */
  1059.     break;
  1060.   case '~':            /* home directory */
  1061.     if (name[1] == '/') t = myhomedir ();
  1062.     else {
  1063.       strcpy (tmp,name + 1);    /* copy user name */
  1064.       if (s = strchr (tmp,'/')) *s = '\0';
  1065.       t = ((pw = getpwnam (tmp)) && pw->pw_dir) ? pw->pw_dir : "/NOSUCHUSER";
  1066.     }
  1067.     sprintf (dst,"%s%s",t,(s = strchr (name,'/')) ? s : "");
  1068.     break;
  1069.   default:            /* other name */
  1070.     if (strcmp (ucase (strcpy (dst,name)),"INBOX"))
  1071.       sprintf (dst,"%s/%s",myhomedir (),name);
  1072.                 /* INBOX becomes mail spool directory file */
  1073.     else sprintf (dst,MAILFILE,myusername ());
  1074.   }
  1075.   return dst;
  1076. }
  1077.  
  1078. /* MMDF open and lock mailbox
  1079.  * Accepts: file name to open/lock
  1080.  *        file open mode
  1081.  *        destination buffer for lock file name
  1082.  *        type of locking operation (LOCK_SH or LOCK_EX)
  1083.  */
  1084.  
  1085. int mmdf_lock (char *file,int flags,int mode,char *lock,int op)
  1086. {
  1087.   int fd,ld,j;
  1088.   int i = LOCKTIMEOUT * 60 - 1;
  1089.   char tmp[MAILTMPLEN];
  1090.   struct timeval tp;
  1091.   struct stat sb;
  1092.                 /* build lock filename */
  1093.   strcat (mmdf_file (lock,file),".lock");
  1094.   do {                /* until OK or out of tries */
  1095.     gettimeofday (&tp,NIL);    /* get the time now */
  1096. #ifdef NFSKLUDGE
  1097.   /* SUN-OS had an NFS, As kludgy as an albatross;
  1098.    * And everywhere that it was installed, It was a total loss.  -- MRC 9/25/91
  1099.    */
  1100.                 /* build hitching post file name */
  1101.     sprintf (tmp,"%s.%d.%d.",lock,time (0),getpid ());
  1102.     j = strlen (tmp);        /* append local host name */
  1103.     gethostname (tmp + j,(MAILTMPLEN - j) - 1);
  1104.                 /* try to get hitching-post file */
  1105.     if ((ld = open (tmp,O_WRONLY|O_CREAT|O_EXCL,0666)) < 0) {
  1106.                 /* prot fail & non-ex, don't use lock files */
  1107.       if ((errno == EACCES) && (stat (tmp,&sb))) *lock = '\0';
  1108.       else {            /* otherwise something strange is going on */
  1109.     sprintf (tmp,"Error creating %s: %s",lock,strerror (errno));
  1110.     mm_log (tmp,WARN);    /* this is probably not good */
  1111.                 /* don't use lock files if not one of these */
  1112.     if ((errno != EEXIST) && (errno != EACCES)) *lock = '\0';
  1113.       }
  1114.     }
  1115.     else {            /* got a hitching-post */
  1116.       chmod (tmp,0666);        /* make sure others can break the lock */
  1117.       close (ld);        /* close the hitching-post */
  1118.       link (tmp,lock);        /* tie hitching-post to lock, ignore failure */
  1119.       stat (tmp,&sb);        /* get its data */
  1120.       unlink (tmp);        /* flush hitching post */
  1121.       /* If link count .ne. 2, hitch failed.  Set ld to -1 as if open() failed
  1122.      so we try again.  If extant lock file and time now is .gt. file time
  1123.      plus timeout interval, flush the lock so can win next time around. */
  1124.       if ((ld = (sb.st_nlink != 2) ? -1 : 0) && (!stat (lock,&sb)) &&
  1125.       (tp.tv_sec > sb.st_ctime + LOCKTIMEOUT * 60)) unlink (lock);
  1126.     }
  1127.  
  1128. #else
  1129.   /* This works on modern Unix systems which are not afflicted with NFS mail.
  1130.    * "Modern" means that O_EXCL works.  I think that NFS mail is a terrible
  1131.    * idea -- that's what IMAP is for -- but some people insist upon losing...
  1132.    */
  1133.                 /* try to get the lock */
  1134.     if ((ld = open (lock,O_WRONLY|O_CREAT|O_EXCL,0666)) < 0) switch (errno) {
  1135.     case EEXIST:        /* if extant and old, grab it for ourselves */
  1136.       if ((!stat (lock,&sb)) && tp.tv_sec > sb.st_ctime + LOCKTIMEOUT * 60)
  1137.     ld = open (lock,O_WRONLY|O_CREAT,0666);
  1138.       break;
  1139.     case EACCES:        /* protection fail, ignore if non-ex or old */
  1140.       if (stat (lock,&sb) || (tp.tv_sec > sb.st_ctime + LOCKTIMEOUT * 60))
  1141.     *lock = '\0';        /* assume no world write mail spool dir */
  1142.       break;
  1143.     default:            /* some other failure */
  1144.       sprintf (tmp,"Error creating %s: %s",lock,strerror (errno));
  1145.       mm_log (tmp,WARN);    /* this is probably not good */
  1146.       *lock = '\0';        /* don't use lock files */
  1147.       break;
  1148.     }
  1149.     if (ld >= 0) {        /* if made a lock file */
  1150.       chmod (tmp,0666);        /* make sure others can break the lock */
  1151.       close (ld);        /* close the lock file */
  1152.     }
  1153. #endif
  1154.     if ((ld < 0) && *lock) {    /* if failed to make lock file and retry OK */
  1155.       if (!(i%15)) {
  1156.     sprintf (tmp,"Mailbox %s is locked, will override in %d seconds...",
  1157.          file,i);
  1158.     mm_log (tmp,WARN);
  1159.       }
  1160.       sleep (1);        /* wait 1 second before next try */
  1161.     }
  1162.   } while (i-- && ld < 0 && *lock);
  1163.                 /* open file */
  1164.   if ((fd = open (file,flags,mode)) >= 0) flock (fd,op);
  1165.   else {            /* open failed */
  1166.     j = errno;            /* preserve error code */
  1167.     if (*lock) unlink (lock);    /* flush the lock file if any */
  1168.     errno = j;            /* restore error code */
  1169.   }
  1170.   return fd;
  1171. }
  1172.  
  1173. /* MMDF unlock and close mailbox
  1174.  * Accepts: file descriptor
  1175.  *        (optional) mailbox stream to check atime/mtime
  1176.  *        (optional) lock file name
  1177.  */
  1178.  
  1179. void mmdf_unlock (int fd,MAILSTREAM *stream,char *lock)
  1180. {
  1181.   struct stat sbuf;
  1182.   struct timeval tp[2];
  1183.   fstat (fd,&sbuf);        /* get file times */
  1184.                 /* if stream and csh would think new mail */
  1185.   if (stream && (sbuf.st_atime <= sbuf.st_mtime)) {
  1186.     gettimeofday (&tp[0],NIL);    /* set atime to now */
  1187.                 /* set mtime to (now - 1) if necessary */
  1188.     tp[1].tv_sec = tp[0].tv_sec > sbuf.st_mtime ? sbuf.st_mtime :
  1189.       tp[0].tv_sec - 1;
  1190.     tp[1].tv_usec = 0;        /* oh well */
  1191.                 /* set the times, note change */
  1192.     if (!utimes (LOCAL->name,tp)) LOCAL->filetime = tp[1].tv_sec;
  1193.   }
  1194.   flock (fd,LOCK_UN);        /* release flock'ers */
  1195.   close (fd);            /* close the file */
  1196.                 /* flush the lock file if any */
  1197.   if (lock && *lock) unlink (lock);
  1198. }
  1199.  
  1200. /* MMDF mail parse and lock mailbox
  1201.  * Accepts: MAIL stream
  1202.  *        space to write lock file name
  1203.  *        type of locking operation
  1204.  * Returns: file descriptor if parse OK, mailbox is locked shared
  1205.  *        -1 if failure, stream aborted
  1206.  */
  1207.  
  1208. int mmdf_parse (MAILSTREAM *stream,char *lock,int op)
  1209. {
  1210.   int fd;
  1211.   long delta,i,j,is,is1;
  1212.   char *s,*s1,*t,*e;
  1213.   int ti,zn;
  1214.   int first = T;
  1215.   long nmsgs = stream->nmsgs;
  1216.   long recent = stream->recent;
  1217.   struct stat sbuf;
  1218.   MESSAGECACHE *elt;
  1219.   FILECACHE *m = NIL,*n;
  1220.   mail_lock (stream);        /* guard against recursion or pingers */
  1221.                 /* open and lock mailbox (shared OK) */
  1222.   if ((fd = mmdf_lock (LOCAL->name,LOCAL->ld ? O_RDWR : O_RDONLY,NIL,
  1223.              lock,op)) < 0) {
  1224.                 /* failed, OK for non-ex file? */
  1225.     if ((errno != ENOENT) || LOCAL->filesize) {
  1226.       sprintf (LOCAL->buf,"Mailbox open failed, aborted: %s",strerror (errno));
  1227.       mm_log (LOCAL->buf,ERROR);
  1228.       mmdf_abort (stream);
  1229.     }
  1230.     else {            /* this is to allow for non-ex INBOX */
  1231.       mail_exists (stream,0);    /* make sure upper level sees this as empty */
  1232.       mail_recent (stream,0);
  1233.     }
  1234.     mail_unlock (stream);
  1235.     return -1;
  1236.   }
  1237.   fstat (fd,&sbuf);        /* get status */
  1238.                 /* calculate change in size */
  1239.   if ((delta = sbuf.st_size - LOCAL->filesize) < 0) {
  1240.     sprintf (LOCAL->buf,"Mailbox shrank from %d to %d bytes, aborted",
  1241.          LOCAL->filesize,sbuf.st_size);
  1242.     mm_log (LOCAL->buf,ERROR);    /* this is pretty bad */
  1243.     mmdf_unlock (fd,stream,lock);
  1244.     mmdf_abort (stream);
  1245.     mail_unlock (stream);
  1246.     return -1;
  1247.   }
  1248.  
  1249.   else if (delta) {        /* get to that position in the file */
  1250.     lseek (fd,LOCAL->filesize,L_SET);
  1251.     s = s1 = LOCAL->buf;    /* initial read-in location */
  1252.     i = 0;            /* initial unparsed read-in count */
  1253.     do {
  1254.       i = min (CHUNK,delta);    /* calculate read-in size */
  1255.                 /* increase the read-in buffer if necessary */
  1256.       if ((j = i + (s1 - s)) >= LOCAL->buflen) {
  1257.     is = s - LOCAL->buf;    /* note former start of message position */
  1258.     is1 = s1 - LOCAL->buf;    /* and start of new data position */
  1259.     if (s1 - s) fs_resize ((void **) &LOCAL->buf,(LOCAL->buflen = j) + 1);
  1260.     else {            /* fs_resize would do an unnecessary copy */
  1261.       fs_give ((void **) &LOCAL->buf);
  1262.       LOCAL->buf = (char *) fs_get ((LOCAL->buflen = j) + 1);
  1263.     }
  1264.     s = LOCAL->buf + is;    /* new start of message */
  1265.     s1 = LOCAL->buf + is1;    /* new start of new data */
  1266.       }
  1267.       s1[i] = '\0';        /* tie off chunk */
  1268.       if (read (fd,s1,i) < 0) {    /* read a chunk of new text */
  1269.     sprintf (LOCAL->buf,"Error reading mail file: %s",strerror (errno));
  1270.     mm_log (LOCAL->buf,ERROR);
  1271.     mmdf_unlock (fd,stream,lock);
  1272.     mmdf_abort (stream);
  1273.     mail_unlock (stream);
  1274.     return -1;
  1275.       }
  1276.       delta -= i;        /* account for data read in */
  1277.                 /* validate newly-appended data */
  1278.       if (first) {        /* only do this first time! */
  1279.     if (!((*s ==(char)0x01) && VALID (s,t,ti,zn))) {
  1280.       mm_log ("Mailbox format invalidated (consult an expert), aborted",
  1281.           ERROR);
  1282.       mmdf_unlock (fd,stream,lock);
  1283.       mmdf_abort (stream);
  1284.       mail_unlock (stream);
  1285.       return -1;
  1286.     }
  1287.     first = NIL;        /* don't do this again */
  1288.       }
  1289.  
  1290.                 /* found end of message or end of data? */
  1291.       while ((e = mmdf_eom (s,s1,i)) || !delta) {
  1292.     nmsgs++;        /* yes, have a new message */
  1293.     if (e) j = (e - s) - 1;    /* calculate message length */
  1294.     else j = strlen (s) - 1;/* otherwise is remainder of data */
  1295.     if (m) {        /* new cache needed, have previous data? */
  1296.       n->header = (char *) fs_get (sizeof (FILECACHE) + j + 1);
  1297.       n = (FILECACHE *) n->header;
  1298.     }
  1299.     else m = n = (FILECACHE *) fs_get (sizeof (FILECACHE) + j + 1);
  1300.                 /* copy message data */
  1301.     strncpy (n->internal,s,j);
  1302.     n->internal[j] = '\0';
  1303.     n->header = NIL;    /* initially no link */
  1304.     n->headersize = j;    /* stash away buffer length */
  1305.     if (e) {        /* saw end of message? */
  1306.       i -= e - s1;        /* new unparsed data count */
  1307.       s = s1 = e;        /* advance to new message */
  1308.     }
  1309.     else break;        /* else punt this loop */
  1310.       }
  1311.       if (delta) {        /* end of message not found? */
  1312.     s1 += i;        /* end of unparsed data */
  1313.     if (s != LOCAL->buf){    /* message doesn't begin at buffer? */
  1314.       i = s1 - s;        /* length of message so far */
  1315.       memmove (LOCAL->buf,s,i);
  1316.       s = LOCAL->buf;    /* message now starts at buffer origin */
  1317.       s1 = s + i;        /* calculate new end of unparsed data */
  1318.     }
  1319.       }
  1320.     } while (delta);        /* until nothing more new to read */
  1321.   }
  1322.   else {            /* no change, don't babble if never got time */
  1323.     if (LOCAL->filetime && LOCAL->filetime != sbuf.st_mtime)
  1324.       mm_log ("New mailbox modification time but apparently no changes",WARN);
  1325.   }
  1326.                 /* expand the primary cache */
  1327.   (*mailcache) (stream,nmsgs,CH_SIZE);
  1328.   if (LOCAL->msgs) {        /* have a cache yet? */
  1329.     if (nmsgs >= LOCAL->cachesize)
  1330.       fs_resize ((void **) &LOCAL->msgs,
  1331.          (LOCAL->cachesize += CACHEINCREMENT) * sizeof (FILECACHE *));
  1332.   }
  1333.   else LOCAL->msgs = (FILECACHE **)
  1334.     fs_get ((LOCAL->cachesize = nmsgs + CACHEINCREMENT) *sizeof (FILECACHE *));
  1335.  
  1336.   if (LOCAL->buflen > CHUNK) {    /* maybe move where the buffer is in memory*/
  1337.     fs_give ((void **) &LOCAL->buf);
  1338.     LOCAL->buf = (char *) fs_get ((LOCAL->buflen = CHUNK) + 1);
  1339.   }
  1340.   for (i = stream->nmsgs, n = m; i < nmsgs; i++) {
  1341.     LOCAL->msgs[i] = m = n;    /* set cache, and next cache pointer */
  1342.     n = (FILECACHE *) n->header;
  1343.     /* This is a bugtrap for bogons in the new message cache, which may happen
  1344.      * if memory is corrupted.  Note that in the case of a totally empty
  1345.      * message, a newline is appended and counts adjusted.
  1346.      */
  1347.     if ((!((s = m->internal) && VALID (s,t,ti,zn))) &&
  1348.     !(s && !strchr (s,'\n') && strcat (s,"\n") && VALID (s,t,ti,zn) &&
  1349.       m->headersize++)) fatal ("Bogus entry in new cache list");
  1350.                 /* pointer to message header */
  1351.     m->header = s = strchr (t++,'\n') + 1;
  1352.     m->headersize -= m->header - m->internal;
  1353.     m->body = NIL;        /* assume no body as yet */
  1354.     m->bodysize = 0;
  1355.     recent++;            /* assume recent by default */
  1356.     (elt = mail_elt (stream,i+1))->recent = T;
  1357.                 /* calculate initial Status/X-Status lines */
  1358.     mmdf_update_status (m->status,elt);
  1359.                 /* generate plausable IMAPish date string */
  1360.     LOCAL->buf[2] = LOCAL->buf[6] = LOCAL->buf[20] = '-';
  1361.     LOCAL->buf[11] = ' ';
  1362.     LOCAL->buf[14] = LOCAL->buf[17] = ':';
  1363.                 /* dd */
  1364.     LOCAL->buf[0] = t[ti - 3]; LOCAL->buf[1] = t[ti - 2];
  1365.                 /* mmm */
  1366.     LOCAL->buf[3] = t[ti - 7]; LOCAL->buf[4] = t[ti - 6];
  1367.     LOCAL->buf[5] = t[ti - 5];
  1368.                 /* hh */
  1369.     LOCAL->buf[12] = t[ti]; LOCAL->buf[13] = t[ti + 1];
  1370.                 /* mm */
  1371.     LOCAL->buf[15] = t[ti + 3]; LOCAL->buf[16] = t[ti + 4];
  1372.     if (t[ti += 5] == ':') {    /* ss if present */
  1373.       LOCAL->buf[18] = t[++ti];
  1374.       LOCAL->buf[19] = t[++ti];
  1375.       ti++;            /* move to space */
  1376.     }
  1377.     else LOCAL->buf[18] = LOCAL->buf[19] = '0';
  1378.                 /* yy -- advance over timezone if necessary */
  1379.     if (zn == ++ti) ti += (((t[zn] == '+') || (t[zn] == '-')) ? 6 : 4);
  1380.     LOCAL->buf[7] = t[ti]; LOCAL->buf[8] = t[ti + 1];
  1381.     LOCAL->buf[9] = t[ti + 2]; LOCAL->buf[10] = t[ti + 3];
  1382.                 /* zzz */
  1383.     t = zn ? (t + zn) : "LCL";
  1384.     LOCAL->buf[21] = *t++; LOCAL->buf[22] = *t++; LOCAL->buf[23] = *t++;
  1385.     if ((LOCAL->buf[21] != '+') && (LOCAL->buf[21] != '-'))
  1386.       LOCAL->buf[24] = '\0';
  1387.     else {            /* numeric time zone */
  1388.       LOCAL->buf[24] = *t++; LOCAL->buf[25] = *t++;
  1389.       LOCAL->buf[26] = '\0'; LOCAL->buf[20] = ' ';
  1390.     }
  1391.                 /* set internal date */
  1392.     if (!mail_parse_date (elt,LOCAL->buf)) mm_log ("Unparsable date",WARN);
  1393.  
  1394.     is = 0;            /* initialize newline count */
  1395.     e = NIL;            /* no status stuff yet */
  1396.     do switch (*(t = s)) {    /* look at header lines */
  1397.     case 'X':            /* possible X-Status: line */
  1398.       if (s[1] == '-' && s[2] == 'S') s += 2;
  1399.       else {
  1400.     is++;            /* count another newline */
  1401.     break;            /* this is uninteresting after all */
  1402.       }
  1403.     case 'S':            /* possible Status: line */
  1404.       if (s[1] == 't' && s[2] == 'a' && s[3] == 't' && s[4] == 'u' &&
  1405.       s[5] == 's' && s[6] == ':') {
  1406.     if (!e) e = t;        /* note deletion point */
  1407.     s += 6;            /* advance to status flags */
  1408.     do switch (*s++) {    /* parse flags */
  1409.     case 'R':        /* message read */
  1410.       elt->seen = T;
  1411.       break;
  1412.     case 'O':        /* message old */
  1413.       if (elt->recent) {    /* don't do this more than once! */
  1414.         elt->recent = NIL;
  1415.         recent--;        /* not recent any longer... */
  1416.       }
  1417.       break;
  1418.     case 'D':        /* message deleted */
  1419.       elt->deleted = T;
  1420.       break;
  1421.     case 'F':        /* message flagged */
  1422.       elt ->flagged = T;
  1423.       break;
  1424.     case 'A':        /* message answered */
  1425.       elt ->answered = T;
  1426.       break;
  1427.     default:        /* some other crap */
  1428.       break;
  1429.     } while (*s && *s != '\n');
  1430.                 /* recalculate Status/X-Status lines */
  1431.     mmdf_update_status (m->status,elt);
  1432.       }
  1433.       else is++;        /* otherwise random line */
  1434.       break;
  1435.  
  1436.     case '\n':            /* end of header */
  1437.       m->body = ++s;        /* start of body is here */
  1438.       j = m->body - m->header;    /* new header size */
  1439.                 /* calculate body size */
  1440.       m->bodysize = m->headersize - j;
  1441.       if (e) {            /* saw status poop? */
  1442.     *e++ = '\n';        /* patch in trailing newline */
  1443.     m->headersize = e - m->header;
  1444.       }
  1445.       else m->headersize = j;    /* set header size */
  1446.       s = NIL;            /* don't scan any further */
  1447.       is++;            /* count a newline */
  1448.       break;
  1449.     case '\0':            /* end of message */
  1450.       if (e) {            /* saw status poop? */
  1451.     *e++ = '\n';        /* patch in trailing newline */
  1452.     m->headersize = e - m->header;
  1453.       }
  1454.       is++;            /* count an extra newline here */
  1455.       break;
  1456.     default:            /* anything else is uninteresting */
  1457.       if (e) {            /* have status stuff to worry about? */
  1458.     j = s - e;        /* yuck!!  calculate size of delete area */
  1459.                 /* blat remaining number of bytes down */
  1460.     memmove (e,s,m->header + m->headersize - s);
  1461.     m->headersize -= j;    /* update for new size */
  1462.     e = NIL;        /* no more delete area */
  1463.                 /* tie off old cruft */
  1464.     *(m->header + m->headersize) = '\0';
  1465.       }
  1466.       is++;
  1467.       break;
  1468.     } while (s && (s = strchr (s,'\n')) && s++);
  1469.                 /* count newlines in body */
  1470.     if (s = m->body) while (*s) if (*s++ == '\n') is++;
  1471.     elt->rfc822_size = m->headersize + m->bodysize + is;
  1472.   }
  1473.   if (n) fatal ("Cache link-list inconsistency");
  1474.   while (i < LOCAL->cachesize) LOCAL->msgs[i++] = NIL;
  1475.                 /* update parsed file size and time */
  1476.   LOCAL->filesize = sbuf.st_size;
  1477.   LOCAL->filetime = sbuf.st_mtime;
  1478.   mail_exists (stream,nmsgs);    /* notify upper level of new mailbox size */
  1479.   mail_recent (stream,recent);    /* and of change in recent messages */
  1480.   if (recent) LOCAL->dirty = T;    /* mark dirty so O flags are set */
  1481.   return fd;            /* return the winnage */
  1482. }
  1483.  
  1484. /* MMDF search for end of message
  1485.  * Accepts: start of message
  1486.  *        start of new data
  1487.  *        size of new data
  1488.  * Returns: pointer to start of new message if one found
  1489.  */
  1490.  
  1491. #define Word unsigned long
  1492.  
  1493. char *mmdf_eom (char *som,char *sod,long i)
  1494. {
  1495.   char *s = sod;        /* find start of line in current message */
  1496.   char *t;
  1497.   int ti,zn;
  1498.   union {
  1499.     unsigned long wd;
  1500.     char ch[9];
  1501.   } wdtest;
  1502.   strcpy (wdtest.ch,"AAAA1234");/* constant for word testing */
  1503.   while ((s > som) && *s-- != '\n');
  1504.   if (wdtest.wd != 0x41414141) {/* not a 32-bit word machine? */
  1505.     while (s = strstr (s,"\nFrom ")) if (s++ && VALID (s,t,ti,zn)) return s;
  1506.   }
  1507.   else {            /* can do it faster this way */
  1508.     register Word m = 0x0a0a0a0a;
  1509.     while ((long) s & 3)    /* any characters before word boundary? */
  1510.       if ((*s++ == '\n') && s[0] == (char)0x01 && VALID (s,t,ti,zn)) return s;
  1511.     i = (sod + i) - s;        /* total number of tries */
  1512.     do {            /* fast search for newline */
  1513.       if (0x80808080 & (0x01010101 + (0x7f7f7f7f & ~(m ^ *(Word *) s)))) {
  1514.                 /* interesting word, check it closer */
  1515.     if (*s++ == '\n' && s[0] == (char)0x01 && VALID (s,t,ti,zn)) return s;
  1516.     else if (*s++ == '\n' && s[0] == (char)0x01 && VALID (s,t,ti,zn)) return s;
  1517.     else if (*s++ == '\n' && s[0] == (char)0x01 && VALID (s,t,ti,zn)) return s;
  1518.     else if (*s++ == '\n' && s[0] == (char)0x01 && VALID (s,t,ti,zn)) return s;
  1519.       }
  1520.       else s += 4;        /* try next word */
  1521.       i -= 4;            /* count a word checked */
  1522.     } while (i > 24);        /* continue until end of plausible string */
  1523.   }
  1524.   return NIL;
  1525. }
  1526.  
  1527. /* MMDF extend mailbox to reserve worst-case space for expansion
  1528.  * Accepts: MAIL stream
  1529.  *        file descriptor
  1530.  *        error string
  1531.  * Returns: T if extend OK and have gone critical, NIL if should abort
  1532.  */
  1533.  
  1534. int mmdf_extend (MAILSTREAM *stream,int fd,char *error)
  1535. {
  1536.   struct stat sbuf;
  1537.   FILECACHE *m;
  1538.   char tmp[MAILTMPLEN];
  1539.   int i,ok;
  1540.   long f;
  1541.   char *s;
  1542.   int retry;
  1543.                 /* calculate estimated size of mailbox */
  1544.   for (i = 0,f = 0; i < stream->nmsgs; i++) {
  1545.     m = LOCAL->msgs[i];        /* get cache pointer */
  1546.     f += (m->header - m->internal) + m->headersize + sizeof (STATUS) +
  1547.       m->bodysize + 1;        /* update guesstimate */
  1548.     }
  1549.   mm_critical (stream);        /* go critical */
  1550.                 /* return now if file large enough */
  1551.   if (f <= LOCAL->filesize) return T;
  1552.   s = (char *) fs_get (f -= LOCAL->filesize);
  1553.   memset (s,0,f);        /* get a block of nulls */
  1554.                 /* get to end of file */
  1555.   lseek (fd,LOCAL->filesize,L_SET);
  1556.   do {
  1557.     retry = NIL;        /* no retry yet */
  1558.     if (!(ok = (write (fd,s,f) >= 0))) {
  1559.       i = errno;        /* note error before doing ftruncate */
  1560.                 /* restore prior file size */
  1561.       ftruncate (fd,LOCAL->filesize);
  1562.       fsync (fd);        /* is this necessary? */
  1563.       fstat (fd,&sbuf);        /* now get updated file time */
  1564.       LOCAL->filetime = sbuf.st_mtime;
  1565.                 /* punt if that's what main program wants */
  1566.       if (mm_diskerror (stream,i,NIL)) {
  1567.     mm_nocritical (stream);    /* exit critical */
  1568.     sprintf (tmp,"%s: %s",error,strerror (i));
  1569.     mm_notify (stream,tmp,WARN);
  1570.       }
  1571.       else retry = T;        /* set to retry */
  1572.     }
  1573.   } while (retry);        /* repeat if need to try again */
  1574.   fs_give ((void **) &s);    /* flush buffer of nulls */
  1575.   return ok;            /* return status */
  1576. }
  1577.  
  1578. /* MMDF save mailbox
  1579.  * Accepts: MAIL stream
  1580.  *        mailbox file descriptor
  1581.  *
  1582.  * Mailbox must be readwrite and locked for exclusive access.
  1583.  */
  1584.  
  1585. void mmdf_save (MAILSTREAM *stream,int fd)
  1586. {
  1587.   struct stat sbuf;
  1588.   struct iovec iov[16];
  1589.   int iovc;
  1590.   long i;
  1591.   int e;
  1592.   int retry;
  1593.   do {                /* restart point if failure */
  1594.     retry = NIL;        /* no need to retry yet */
  1595.                 /* start at beginning of file */
  1596.     lseek (fd,LOCAL->filesize = 0,L_SET);
  1597.                 /* loop through all messages */
  1598.     for (i = 1,iovc = 0; i <= stream->nmsgs; i++) {
  1599.                 /* set up iov's for this message */
  1600.       mmdf_write_message (iov,&iovc,LOCAL->msgs[i-1]);
  1601.                 /* filled up iovec or end of messages? */
  1602.       if ((iovc == 16) || (i == stream->nmsgs)) {
  1603.                 /* write messages */
  1604.     if ((e = writev (fd,iov,iovc)) < 0) {
  1605.       sprintf (LOCAL->buf,"Unable to rewrite mailbox: %s",
  1606.            strerror (e = errno));
  1607.       mm_log (LOCAL->buf,WARN);
  1608.       mm_diskerror (stream,e,T);
  1609.       retry = T;        /* must retry */
  1610.       break;        /* abort this particular try */
  1611.     }
  1612.     else {            /* won */
  1613.       iovc = 0;        /* restart iovec */
  1614.       LOCAL->filesize += e;    /* count these bytes in data */
  1615.     }
  1616.       }
  1617.     }
  1618.   } while (retry);        /* repeat if need to try again */
  1619.   fsync (fd);            /* make sure the disk has the update */
  1620.                 /* nuke any cruft after that */
  1621.   ftruncate (fd,LOCAL->filesize);
  1622.   fsync (fd);            /* is this necessary? */
  1623.   fstat (fd,&sbuf);        /* now get updated file time */
  1624.   LOCAL->filetime = sbuf.st_mtime;
  1625.   LOCAL->dirty = NIL;        /* stream no longer dirty */
  1626.   mm_nocritical (stream);    /* exit critical */
  1627. }
  1628.  
  1629. /* MMDF copy messages
  1630.  * Accepts: MAIL stream
  1631.  *        mailbox name
  1632.  * Returns: T if copy successful else NIL
  1633.  */
  1634.  
  1635. int mmdf_copy_messages (MAILSTREAM *stream,char *mailbox)
  1636. {
  1637.   char file[MAILTMPLEN];
  1638.   char lock[MAILTMPLEN];
  1639.   struct iovec iov[16];
  1640.   int fd,iovc;
  1641.   struct stat sbuf;
  1642.   long i;
  1643.   int ok = T;
  1644.                 /* make sure valid mailbox */
  1645.   if (!mmdf_isvalid (mailbox,file)) {
  1646.     sprintf (LOCAL->buf,"Not a MMDF-format mailbox: %s",mailbox);
  1647.     mm_log (LOCAL->buf,ERROR);
  1648.     return NIL;
  1649.   }
  1650.   if ((fd = mmdf_lock (mmdf_file (file,mailbox),O_WRONLY|O_APPEND|O_CREAT,
  1651.              S_IREAD|S_IWRITE,lock,LOCK_EX)) < 0) {
  1652.     sprintf (LOCAL->buf,"Can't open destination mailbox: %s",strerror (errno));
  1653.     mm_log (LOCAL->buf,ERROR);
  1654.     return NIL;
  1655.   }
  1656.   mm_critical (stream);        /* go critical */
  1657.   fstat (fd,&sbuf);        /* get current file size */
  1658.                 /* write all requested messages to mailbox */
  1659.   for (i = 1,iovc = 0; ok && i <= stream->nmsgs; i++) {
  1660.                 /* set up iov's if message selected */
  1661.     if (mail_elt (stream,i)->sequence)
  1662.       mmdf_write_message (iov,&iovc,LOCAL->msgs[i - 1]);
  1663.                 /* filled up iovec or end of messages? */
  1664.     if (iovc && ((iovc == 16) || (i == stream->nmsgs))) {
  1665.       if (ok = (writev (fd,iov,iovc) >= 0)) iovc = 0;
  1666.       else {
  1667.     sprintf (LOCAL->buf,"Message copy failed: %s",strerror (errno));
  1668.     mm_log (LOCAL->buf,ERROR);
  1669.     ftruncate (fd,sbuf.st_size);
  1670.     break;
  1671.       }
  1672.     }
  1673.   }
  1674.   fsync (fd);            /* force out the update */
  1675.   mmdf_unlock (fd,NIL,lock);    /* unlock and close mailbox */
  1676.   mm_nocritical (stream);    /* release critical */
  1677.   return ok;            /* return whether or not succeeded */
  1678. }
  1679.  
  1680. /* MMDF write message to mailbox
  1681.  * Accepts: I/O vector
  1682.  *        I/O vector index
  1683.  *        local cache for this message
  1684.  *
  1685.  * This routine is the reason why the local cache has a copy of the status.
  1686.  * We can be called to dump out the mailbox as part of a stream recycle, since
  1687.  * we don't write out the mailbox when flags change and hence an update may be
  1688.  * needed.  However, at this point the elt has already become history, so we
  1689.  * can't use any information other than what is local to us.
  1690.  */
  1691.  
  1692. void mmdf_write_message (struct iovec iov[],int *i,FILECACHE *m)
  1693. {
  1694.   iov[*i].iov_base =m->internal;/* pointer/counter to headers */
  1695.                 /* length of internal + message headers */
  1696.   iov[*i].iov_len = (m->header + m->headersize) - m->internal;
  1697.                 /* suppress extra newline if present */
  1698.   if ((iov[*i].iov_base)[iov[*i].iov_len - 2] == '\n') iov[(*i)++].iov_len--;
  1699.   else (*i)++;            /* unlikely but... */
  1700.   iov[*i].iov_base = m->status;    /* pointer/counter to status */
  1701.   iov[(*i)++].iov_len = strlen (m->status);
  1702.   iov[*i].iov_base = m->body;    /* pointer/counter to text body */
  1703.   iov[(*i)++].iov_len = m->bodysize;
  1704.   iov[*i].iov_base = "\n";    /* pointer/counter to extra newline */
  1705.   iov[(*i)++].iov_len = 1;
  1706. }
  1707.  
  1708. /* MMDF update status string
  1709.  * Accepts: destination string to write
  1710.  *        message cache entry
  1711.  */
  1712.  
  1713. void mmdf_update_status (char *status,MESSAGECACHE *elt)
  1714. {
  1715.   /* This used to be an sprintf(), but thanks to certain cretinous C libraries
  1716.      with horribly slow implementations of sprintf() I had to change it to this
  1717.      mess.  At least it should be fast. */
  1718.   char *t = status + 8;
  1719.   status[0] = 'S'; status[1] = 't'; status[2] = 'a'; status[3] = 't';
  1720.   status[4] = 'u'; status[5] = 's'; status[6] = ':';  status[7] = ' ';
  1721.   if (elt->seen) *t++ = 'R'; *t++ = 'O'; *t++ = '\n';
  1722.   *t++ = 'X'; *t++ = '-'; *t++ = 'S'; *t++ = 't'; *t++ = 'a'; *t++ = 't';
  1723.   *t++ = 'u'; *t++ = 's'; *t++ = ':'; *t++ = ' ';
  1724.   if (elt->deleted) *t++ = 'D'; if (elt->flagged) *t++ = 'F';
  1725.   if (elt->answered) *t++ = 'A';
  1726.   *t++ = '\n'; *t++ = '\n'; *t++ = '\0';
  1727. }
  1728.  
  1729. /* Parse flag list
  1730.  * Accepts: MAIL stream
  1731.  *        flag list as a character string
  1732.  * Returns: flag command list
  1733.  */
  1734.  
  1735.  
  1736. short mmdf_getflags (MAILSTREAM *stream,char *flag)
  1737. {
  1738.   char *t;
  1739.   short f = 0;
  1740.   short i,j;
  1741.   if (flag && *flag) {        /* no-op if no flag string */
  1742.                 /* check if a list and make sure valid */
  1743.     if ((i = (*flag == '(')) ^ (flag[strlen (flag)-1] == ')')) {
  1744.       mm_log ("Bad flag list",ERROR);
  1745.       return NIL;
  1746.     }
  1747.                 /* copy the flag string w/o list construct */
  1748.     strncpy (LOCAL->buf,flag+i,(j = strlen (flag) - (2*i)));
  1749.     LOCAL->buf[j] = '\0';
  1750.     t = ucase (LOCAL->buf);    /* uppercase only from now on */
  1751.  
  1752.     while (*t) {        /* parse the flags */
  1753.       if (*t == '\\') {        /* system flag? */
  1754.     switch (*++t) {        /* dispatch based on first character */
  1755.     case 'S':        /* possible \Seen flag */
  1756.       if (t[1] == 'E' && t[2] == 'E' && t[3] == 'N') i = fSEEN;
  1757.       t += 4;        /* skip past flag name */
  1758.       break;
  1759.     case 'D':        /* possible \Deleted flag */
  1760.       if (t[1] == 'E' && t[2] == 'L' && t[3] == 'E' && t[4] == 'T' &&
  1761.           t[5] == 'E' && t[6] == 'D') i = fDELETED;
  1762.       t += 7;        /* skip past flag name */
  1763.       break;
  1764.     case 'F':        /* possible \Flagged flag */
  1765.       if (t[1] == 'L' && t[2] == 'A' && t[3] == 'G' && t[4] == 'G' &&
  1766.           t[5] == 'E' && t[6] == 'D') i = fFLAGGED;
  1767.       t += 7;        /* skip past flag name */
  1768.       break;
  1769.     case 'A':        /* possible \Answered flag */
  1770.       if (t[1] == 'N' && t[2] == 'S' && t[3] == 'W' && t[4] == 'E' &&
  1771.           t[5] == 'R' && t[6] == 'E' && t[7] == 'D') i = fANSWERED;
  1772.       t += 8;        /* skip past flag name */
  1773.       break;
  1774.     default:        /* unknown */
  1775.       i = 0;
  1776.       break;
  1777.     }
  1778.                 /* add flag to flags list */
  1779.     if (i && ((*t == '\0') || (*t++ == ' '))) f |= i;
  1780.     else {            /* bitch about bogus flag */
  1781.       mm_log ("Unknown system flag",ERROR);
  1782.       return NIL;
  1783.     }
  1784.       }
  1785.       else {            /* no user flags yet */
  1786.     mm_log ("Unknown flag",ERROR);
  1787.     return NIL;
  1788.       }
  1789.     }
  1790.   }
  1791.   return f;
  1792. }
  1793.  
  1794. /* Search support routines
  1795.  * Accepts: MAIL stream
  1796.  *        message number
  1797.  *        pointer to additional data
  1798.  * Returns: T if search matches, else NIL
  1799.  */
  1800.  
  1801.  
  1802. char mmdf_search_all (MAILSTREAM *stream,long msgno,char *d,long n)
  1803. {
  1804.   return T;            /* ALL always succeeds */
  1805. }
  1806.  
  1807.  
  1808. char mmdf_search_answered (MAILSTREAM *stream,long msgno,char *d,long n)
  1809. {
  1810.   return mail_elt (stream,msgno)->answered ? T : NIL;
  1811. }
  1812.  
  1813.  
  1814. char mmdf_search_deleted (MAILSTREAM *stream,long msgno,char *d,long n)
  1815. {
  1816.   return mail_elt (stream,msgno)->deleted ? T : NIL;
  1817. }
  1818.  
  1819.  
  1820. char mmdf_search_flagged (MAILSTREAM *stream,long msgno,char *d,long n)
  1821. {
  1822.   return mail_elt (stream,msgno)->flagged ? T : NIL;
  1823. }
  1824.  
  1825.  
  1826. char mmdf_search_keyword (MAILSTREAM *stream,long msgno,char *d,long n)
  1827. {
  1828.   return NIL;            /* keywords not supported yet */
  1829. }
  1830.  
  1831.  
  1832. char mmdf_search_new (MAILSTREAM *stream,long msgno,char *d,long n)
  1833. {
  1834.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  1835.   return (elt->recent && !elt->seen) ? T : NIL;
  1836. }
  1837.  
  1838. char mmdf_search_old (MAILSTREAM *stream,long msgno,char *d,long n)
  1839. {
  1840.   return mail_elt (stream,msgno)->recent ? NIL : T;
  1841. }
  1842.  
  1843.  
  1844. char mmdf_search_recent (MAILSTREAM *stream,long msgno,char *d,long n)
  1845. {
  1846.   return mail_elt (stream,msgno)->recent ? T : NIL;
  1847. }
  1848.  
  1849.  
  1850. char mmdf_search_seen (MAILSTREAM *stream,long msgno,char *d,long n)
  1851. {
  1852.   return mail_elt (stream,msgno)->seen ? T : NIL;
  1853. }
  1854.  
  1855.  
  1856. char mmdf_search_unanswered (MAILSTREAM *stream,long msgno,char *d,long n)
  1857. {
  1858.   return mail_elt (stream,msgno)->answered ? NIL : T;
  1859. }
  1860.  
  1861.  
  1862. char mmdf_search_undeleted (MAILSTREAM *stream,long msgno,char *d,long n)
  1863. {
  1864.   return mail_elt (stream,msgno)->deleted ? NIL : T;
  1865. }
  1866.  
  1867.  
  1868. char mmdf_search_unflagged (MAILSTREAM *stream,long msgno,char *d,long n)
  1869. {
  1870.   return mail_elt (stream,msgno)->flagged ? NIL : T;
  1871. }
  1872.  
  1873.  
  1874. char mmdf_search_unkeyword (MAILSTREAM *stream,long msgno,char *d,long n)
  1875. {
  1876.   return T;            /* keywords not supported yet */
  1877. }
  1878.  
  1879.  
  1880. char mmdf_search_unseen (MAILSTREAM *stream,long msgno,char *d,long n)
  1881. {
  1882.   return mail_elt (stream,msgno)->seen ? NIL : T;
  1883. }
  1884.  
  1885. char mmdf_search_before (MAILSTREAM *stream,long msgno,char *d,long n)
  1886. {
  1887.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  1888.   return (char) ((long)((elt->year << 9) + (elt->month << 5) + elt->day) < n);
  1889. }
  1890.  
  1891.  
  1892. char mmdf_search_on (MAILSTREAM *stream,long msgno,char *d,long n)
  1893. {
  1894.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  1895.   return (char) (((elt->year << 9) + (elt->month << 5) + elt->day) == n);
  1896. }
  1897.  
  1898.  
  1899. char mmdf_search_since (MAILSTREAM *stream,long msgno,char *d,long n)
  1900. {
  1901.                 /* everybody interprets "since" as .GE. */
  1902.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  1903.   return (char) ((long)((elt->year << 9) + (elt->month << 5) + elt->day) >= n);
  1904. }
  1905.  
  1906.  
  1907. char mmdf_search_body (MAILSTREAM *stream,long msgno,char *d,long n)
  1908. {
  1909.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  1910.   return search (m->body,m->bodysize,d,n);
  1911. }
  1912.  
  1913.  
  1914. char mmdf_search_subject (MAILSTREAM *stream,long msgno,char *d,long n)
  1915. {
  1916.   char *s = mmdf_fetchstructure (stream,msgno,NIL)->subject;
  1917.   return s ? search (s,strlen (s),d,n) : NIL;
  1918. }
  1919.  
  1920.  
  1921. char mmdf_search_text (MAILSTREAM *stream,long msgno,char *d,long n)
  1922. {
  1923.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  1924.   return search (m->header,m->headersize,d,n) ||
  1925.     mmdf_search_body (stream,msgno,d,n);
  1926. }
  1927.  
  1928. char mmdf_search_bcc (MAILSTREAM *stream,long msgno,char *d,long n)
  1929. {
  1930.   LOCAL->buf[0] = '\0';        /* initially empty string */
  1931.                 /* get text for address */
  1932.   rfc822_write_address (LOCAL->buf,
  1933.             mmdf_fetchstructure (stream,msgno,NIL)->bcc);
  1934.   return search (LOCAL->buf,strlen (LOCAL->buf),d,n);
  1935. }
  1936.  
  1937.  
  1938. char mmdf_search_cc (MAILSTREAM *stream,long msgno,char *d,long n)
  1939. {
  1940.   LOCAL->buf[0] = '\0';        /* initially empty string */
  1941.                 /* get text for address */
  1942.   rfc822_write_address (LOCAL->buf,
  1943.             mmdf_fetchstructure (stream,msgno,NIL)->cc);
  1944.   return search (LOCAL->buf,strlen (LOCAL->buf),d,n);
  1945. }
  1946.  
  1947.  
  1948. char mmdf_search_from (MAILSTREAM *stream,long m,char *d,long n)
  1949. {
  1950.   LOCAL->buf[0] = '\0';        /* initially empty string */
  1951.                 /* get text for address */
  1952.   rfc822_write_address (LOCAL->buf,mmdf_fetchstructure (stream,m,NIL)->from);
  1953.   return search (LOCAL->buf,strlen (LOCAL->buf),d,n);
  1954. }
  1955.  
  1956.  
  1957. char mmdf_search_to (MAILSTREAM *stream,long msgno,char *d,long n)
  1958. {
  1959.   LOCAL->buf[0] = '\0';        /* initially empty string */
  1960.                 /* get text for address */
  1961.   rfc822_write_address (LOCAL->buf,
  1962.             mmdf_fetchstructure (stream,msgno,NIL)->to);
  1963.   return search (LOCAL->buf,strlen (LOCAL->buf),d,n);
  1964. }
  1965.  
  1966. /* Search parsers */
  1967.  
  1968.  
  1969. /* Parse a date
  1970.  * Accepts: function to return
  1971.  *        pointer to date integer to return
  1972.  * Returns: function to return
  1973.  */
  1974.  
  1975. search_t mmdf_search_date (search_t f,long *n)
  1976. {
  1977.   long i;
  1978.   char *s;
  1979.   MESSAGECACHE elt;
  1980.                 /* parse the date and return fn if OK */
  1981.   return (mmdf_search_string (f,&s,&i) && mail_parse_date (&elt,s) &&
  1982.       (*n = (elt.year << 9) + (elt.month << 5) + elt.day)) ? f : NIL;
  1983. }
  1984.  
  1985. /* Parse a flag
  1986.  * Accepts: function to return
  1987.  *        pointer to string to return
  1988.  * Returns: function to return
  1989.  */
  1990.  
  1991. search_t mmdf_search_flag (search_t f,char **d)
  1992. {
  1993.                 /* get a keyword, return if OK */
  1994.   return (*d = strtok (NIL," ")) ? f : NIL;
  1995. }
  1996.  
  1997.  
  1998. /* Parse a string
  1999.  * Accepts: function to return
  2000.  *        pointer to string to return
  2001.  *        pointer to string length to return
  2002.  * Returns: function to return
  2003.  */
  2004.  
  2005.  
  2006. search_t mmdf_search_string (search_t f,char **d,long *n)
  2007. {
  2008.   char *c = strtok (NIL,"");    /* remainder of criteria */
  2009.   if (c) {            /* better be an argument */
  2010.     switch (*c) {        /* see what the argument is */
  2011.     case '\0':            /* catch bogons */
  2012.     case ' ':
  2013.       return NIL;
  2014.     case '"':            /* quoted string */
  2015.       if (!(strchr (c+1,'"') && (*d = strtok (c,"\"")) && (*n = strlen (*d))))
  2016.     return NIL;
  2017.       break;
  2018.     case '{':            /* literal string */
  2019.       *n = strtol (c+1,&c,10);    /* get its length */
  2020.       if (*c++ != '}' || *c++ != '\015' || *c++ != '\012' ||
  2021.       *n > strlen (*d = c)) return NIL;
  2022.       c[*n] = '\255';        /* write new delimiter */
  2023.       strtok (c,"\255");    /* reset the strtok mechanism */
  2024.       break;
  2025.     default:            /* atomic string */
  2026.       *n = strlen (*d = strtok (c," "));
  2027.       break;
  2028.     }
  2029.     return f;
  2030.   }
  2031.   else return NIL;
  2032. }
  2033.